from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from django.core.cache import caches
import json


class UserAgentMiddleware(MiddlewareMixin):
    def process_request(self, request):
        print("UserAgentMiddleware处理请求")
        pass

    def process_response(self, request, response):
        print("UserAgentMiddleware处理响应")
        if request.headers["User-Agent"] not in [
            "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
        ]:
            return HttpResponse("出现错误")
        return response


class ForbiddenIPMiddleware(MiddlewareMixin):
    def process_request(self, request):
        print("ForbiddenIPMiddleware处理请求")
        pass

    def process_response(self, request, response):
        print("ForbiddenIPMiddleware处理响应")
        # print(request.META["REMOTE_ADDR"])
        cache = caches["redis"]
        # 需要封禁的ip加入数据库
        fbs_ips = []
        fbs_ips.append(request.META["REMOTE_ADDR"])
        print(fbs_ips)

        # cache.set("ips", json.dumps(fbs_ips))
        fbs_ips = cache.get("ips")
        fbs_ips = json.loads(fbs_ips)

        current_ip = request.META["REMOTE_ADDR"]
        if current_ip in fbs_ips:
            return HttpResponse("出错了")
        return response
